package com.layui.ad.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.layui.ad.annotation.DataSource;
import com.layui.ad.entity.Role;
import com.layui.ad.entity.SysAdmin;
import com.layui.ad.enums.DataSourceEnum;
import com.layui.ad.mapper.RoleMapper;
import com.layui.ad.mapper.SysAdminMapper;
import com.layui.ad.query.AdminQuery;
import com.layui.ad.service.SysAdminService;
import com.layui.ad.utils.DateUtils;
import com.layui.ad.utils.JsonResult;
import com.layui.ad.utils.ShiroUtils;
import com.layui.ad.utils.StringUtils;
import com.layui.ad.vo.AdminListVo;
import com.layui.ad.vo.AdminPwdVo;
import com.layui.ad.vo.RoleListVo;
import groovy.transform.Internal;
import lombok.Builder;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.*;

@Service
@Log4j2
public class SysAdminServiceImpl extends ServiceImpl<SysAdminMapper, SysAdmin> implements SysAdminService {
    @Autowired
    private SysAdminMapper sysAdminMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public List<SysAdmin> selectRecord() {
        return this.baseMapper.selectRecord();
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public boolean login(String username, String password) {
        Subject user = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 登录
        try {
            user.login(token);
            SysAdmin admin = sysAdminMapper.selectById(ShiroUtils.getAdminId());
            admin.setLoginTime(DateUtils.now());
            admin.setLoginNum(admin.getLoginNum()+1);
            sysAdminMapper.updateById(admin);
            System.out.println("登录成功");
            return true;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("登录失败");
            return false;
        }
    }

    @DataSource(DataSourceEnum.SYSSOURCE)
    @Override
    public SysAdmin findUsername(String username) {
        SysAdmin data = this.baseMapper.findUsername(username);
        return data;
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public SysAdmin getUserInfo(Integer id){
        return sysAdminMapper.selectById(id);
    }


    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public IPage<SysAdmin> getList2(Integer currentPage, Integer limit, String keywords) {
        LambdaQueryWrapper<SysAdmin> lambda = new QueryWrapper<SysAdmin>().lambda();
        Page<SysAdmin> page = new Page<SysAdmin>(currentPage, limit);
//        if (null!=keywords) {
//            lambda.like(SysAdmin::getUsername, keywords).or().like(SysAdmin::getRealname, keywords);
//        }
        IPage<SysAdmin> listData = this.baseMapper.selectPage(page, lambda);
        return listData;
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public JsonResult getList(AdminQuery adminQuery) {
        QueryWrapper<SysAdmin> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(adminQuery.getKeywords())) {
            queryWrapper.like("mobile", adminQuery.getKeywords()).or().like("realname", adminQuery.getKeywords());
        }
        if (adminQuery.getGender() != null) {
            queryWrapper.eq("gender", adminQuery.getGender());
        }
        if (adminQuery.getStatus() != null) {
            queryWrapper.eq("status", adminQuery.getStatus());
        }
        // 查询数据
        IPage<SysAdmin> page = new Page<>(adminQuery.getPage(), adminQuery.getLimit());
        IPage<SysAdmin> data = sysAdminMapper.selectPage(page, queryWrapper);
        List<SysAdmin> adminList = data.getRecords();
        List<AdminListVo> adminListVoList = new ArrayList<>();

        if (!adminList.isEmpty()) {
            adminList.forEach(item -> {
                AdminListVo adminListVo = new AdminListVo();
                // 拷贝属性
                BeanUtils.copyProperties(item, adminListVo);
                adminListVo.setGenderName("保密");
                adminListVoList.add(adminListVo);
            });
        }
        return JsonResult.ok("操作成功", adminListVoList, data.getTotal());
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public JsonResult setStatus(SysAdmin entiry) {
        Integer flag = sysAdminMapper.updateById(entiry);
        if (flag > 0) {
            return JsonResult.ok();
        } else {
            return JsonResult.fail();
        }
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public Map<String, Object> info(Integer id) {
        Object entity = sysAdminMapper.selectById(id);
        Map<String, Object> map = JSON.parseObject(JSON.toJSONString(entity), new TypeReference<Map<String, Object>>() {
        });
        return map;
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public List<Map<String, Object>> getRoleList(String roleIds) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        String[] roleStr = {};
        if (roleIds != null) {
            roleStr = roleIds.split(",");
        }
        List<String> roleList = Arrays.asList(roleStr);

        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",1);
        List<Role> roleListData= roleMapper.selectList(queryWrapper);
        if(!roleListData.isEmpty()){
            roleListData.forEach(item->{
                Map<String,Object> map = new HashMap<>();
                map.put("id",item.getId());
                map.put("name",item.getName());
                if(roleList.contains(item.getId().toString())){
                    map.put("checked",true);
                }else{
                    map.put("checked",false);
                }
                mapList.add(map);
            });
        }

        return mapList;
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public JsonResult edit(SysAdmin entiry){
        Integer count;
        if(StringUtils.isEmpty(entiry.getPassword())){
            entiry.setPassword(null);
        }else{
            String md5Password = DigestUtils.md5DigestAsHex(entiry.getPassword().getBytes());
            entiry.setPassword(md5Password);
        }
        if(entiry.getId()!=null && entiry.getId()>0){
            count = sysAdminMapper.updateById(entiry);
        }else{
            entiry.setCreateTime(DateUtils.now());
            count = sysAdminMapper.insert(entiry);
        }
        if(count>0){
            return JsonResult.ok();
        }else{
            return JsonResult.fail();
        }
    }

    //删除用户
    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public JsonResult deleteById(Integer id){
        if(id==null || id<=0){
            return JsonResult.fail("非法参数");
        }
        if(id == 1){
            return JsonResult.fail("系统保护账号,无法删除");
        }
        SysAdmin admin = sysAdminMapper.selectById(id);
        if(admin == null){
            return JsonResult.fail("账号不存在");
        }
        return JsonResult.ok("删除测试");
//        Integer num = sysAdminMapper.deleteById(id);
//        if(num>0) {
//            return JsonResult.ok();
//        }else{
//            return JsonResult.fail("删除失败");
//        }
    }

    //批量删除用户
    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public JsonResult deleteByIds(String ids){
        if(StringUtils.isEmpty(ids)){
            return JsonResult.fail("参数不能为空");
        }
        String[] item = ids.split(",");
        List<String> itemList = Arrays.asList(item);
        if(itemList.contains("1")){
            return JsonResult.fail("包含不能删除的用户");
        }
        Integer result = sysAdminMapper.deleteBatchIds(itemList);
        if(result>0){
            return JsonResult.ok();
        }else{
            return JsonResult.fail("批量删除失败");
        }
    }

    //修改密码
    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public JsonResult updatePassword(AdminPwdVo entiry){
        if(StringUtils.isEmpty(entiry.getOldPassword())){
            return JsonResult.fail("旧密码不能为空");
        }

        if(StringUtils.isEmpty(entiry.getNewPassword()) || StringUtils.isEmpty(entiry.getRePassword())){
            return JsonResult.fail("新密码或确认密码不能为空");
        }


        if(!entiry.getNewPassword().equals(entiry.getRePassword())){
            return JsonResult.fail("两次输入新密码不一致");
        }
        String oldPassword = DigestUtils.md5DigestAsHex(entiry.getOldPassword().getBytes());
        String newPassword =  DigestUtils.md5DigestAsHex(entiry.getNewPassword().getBytes());

        SysAdmin admin = sysAdminMapper.selectById(ShiroUtils.getAdminId());
        if(admin == null){
            return JsonResult.fail("账号不存在");
        }

        if(!admin.getPassword().equals(oldPassword)){
            return JsonResult.fail("密码错误");
        }

        admin.setPassword(newPassword);
        Integer num = sysAdminMapper.updateById(admin);
        if(num>0) {

            return JsonResult.ok("修改成功");
        }else {
            return JsonResult.fail("密码修改失败");
        }
    }
}
